package com.example.exercise.step.service.impl;

import com.example.exercise.step.documents.*;
import com.example.exercise.step.response.StepsRankAllResp;
import com.example.exercise.step.service.StepService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

@Service
public class StepServiceImpl implements StepService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void uploadStep() {

        int userId = new Random().nextInt(100);
        String name = "user" + userId;
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        Criteria criteria = Criteria.where("groupId").is(10086)
                .and("userId").is(userId)
                .and("name").is(name)
                .and("date").is(date);
        Query query = new Query(criteria);
        List<StepsCount> list = mongoTemplate.find(query, StepsCount.class);
        int stepCount = new Random().nextInt(50);
        //没有查询到步数记录
        if(list.isEmpty()) {
            StepsCount stepsCount = new StepsCount();
            stepsCount.setUserId(userId);
            stepsCount.setName(name);
            stepsCount.setDate(date);
            stepsCount.setGroupId(10086);
            stepsCount.setTotalCount(stepCount);
            mongoTemplate.insert(stepsCount);
        } else {
            StepsCount stepsCount = list.get(0);
            Update update = new Update();
            update.set("totalCount", stepCount + stepsCount.getTotalCount());
            mongoTemplate.upsert(query, update, StepsCount.class);
        }
    }

    @Override
    public List<StepsRankAllResp> getRankToday(int begin, int pageSize) {
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Criteria criteria = Criteria.where("groupId").is(10086).and("date").is(date);
        Query query = new Query(criteria).with(Sort.by(Sort.Direction.DESC,"totalCount")).limit(200);
        List<StepsCount> list = mongoTemplate.find(query, StepsCount.class);
        List<StepsRankAllResp> stepsRankAllResps = new ArrayList<>(pageSize);
        for (int i = 0; i < list.size(); i++) {
            StepsCount step = list.get(i);
            StepsRankAllResp stepsRankAllResp = new StepsRankAllResp();
            BeanUtils.copyProperties(step, stepsRankAllResp);
            stepsRankAllResp.setRank(begin + i);
            stepsRankAllResps.add(stepsRankAllResp);
        }
        return stepsRankAllResps;
    }

    @Override
    public List<StepsRankAllResp> getRankAll(int begin, int pageSize) {
        List<StepsCount> list = this.getStepsTop(begin, pageSize);
        List<StepsRankAllResp> stepsRankAllResps = new ArrayList<>(pageSize);
        for (int i = 0; i < list.size(); i++) {
            StepsCount step = list.get(i);
            StepsRankAllResp stepsRankAllResp = new StepsRankAllResp();
            BeanUtils.copyProperties(step, stepsRankAllResp);
            stepsRankAllResp.setRank(begin + i);
            stepsRankAllResps.add(stepsRankAllResp);
        }
        return stepsRankAllResps;
    }

    private List<StepsCount> getStepsTop(int begin, int pageSize) {
//        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date().getTime() - 7 * 24 * 3600 * 1000);
        TypedAggregation<StepsCount> aggregation = Aggregation.newAggregation(
                StepsCount.class,
                project("groupId", "userId", "name", "totalCount"),//查询用到的字段
                match(Criteria.where("groupId").is(10086)),
                group("userId","name").sum("totalCount").as("totalCount"),
                sort(Sort.Direction.DESC, "totalCount"),
//                project("a", "aa").and("a").previousOperation(),//输出字段,后面是取别名
                skip((long) begin),
                limit(pageSize)
        ).withOptions(newAggregationOptions().allowDiskUse(true).build());//内存不足到磁盘读写，应对高并发
        AggregationResults<StepsCount> results = mongoTemplate.aggregate(aggregation, StepsCount.class, StepsCount.class);
        return results.getMappedResults();
    }

}
